<?php

namespace app\api\controller\store;

use addons\litestore\model\Litestoregoodsspec;
use addons\litestore\model\Wxlitestoregoods;
use addons\wechat\library\Config as ConfigService;
use app\admin\model\litestore\Litestoregoods;
use app\admin\model\litestore\Litestorenews;
use app\admin\model\Profitorder;
use app\admin\model\Profitorderundo;
use app\admin\model\Profitvip;
use app\admin\model\Publishwork;
use app\admin\model\Shopadmin;
use app\admin\model\Shopjob;
use app\admin\model\Shopjobuser;
use app\admin\model\Shopuser;
use app\admin\model\Useramount;
use app\admin\model\Usermsgweixin;
use app\admin\model\Userprofile;
use app\admin\model\Userteamworkhistory;
use app\admin\model\Workaddress;
use app\admin\model\Workhistory;
use app\admin\model\Worktype;
use app\api\service\ProfitService;
use app\common\controller\Api;
use EasyWeChat\Factory;
use fast\Random;
use think\Db;
use think\db\Query;
use think\Exception;

/**
 */
class Shop extends Api
{
    protected $noNeedLogin = ['workList', 'jobDetail', 'init', 'updateOnlineStatus'];
    protected $noNeedRight = ['*'];


    protected $wxapp = null;

    public function _initialize()
    {
        parent::_initialize();

        $config = [
            'app_id' => 'wx763ae61820ee8dc5',
            'secret' => '507d2ecbb6529937dfb6d390e3ff1660',

            'response_type' => 'array',
            'log' => [
                'level' => 'debug',
            ],
        ];
        $this->wxapp = Factory::officialAccount(ConfigService::load());

    }

    public function init()
    {


        $uid = $this->request->param('id');
        $shopModel = new \app\admin\model\Shop();
        $list = $shopModel->where('uid', $uid)->select();
        error_log("===isList====".json_encode($list));
        if ($list != null) {

            if (count($list) == 1) {
                $shopModel->where('id', $list[0]['id'])->update(['is_online' => 1]);
                $this->success('');
            } else {
                $this->success('', $list);
            }
        } else {
            $this->success('');
        }
    }

    public function doUserJob()
    {

        $want = $this->request->param('want');
        $workType = $this->request->param('workType');
        $jobId = $this->request->param('jobId');
        $uid = $this->request->param('uid');
        error_log("====uid===" . $uid);
        $user = $this->auth->getUser();
        $shopModel = new \app\admin\model\Shop();
        $shop = $this->adminShopInfo($user['id']);
        $shopId = $shop['id'];

        $shopJobUserModel = new Shopjobuser();
        $shopJob = $shopJobUserModel->where('uid', $uid)->where('shopid', $shopId)->find();

        error_log("===shopJob====" . json_encode($shopJob));
        if ($shopJob['status'] != -1) {
            $this->error('请勿重复处理');
        }
        $shopJobUserModel->where('id', $shopJob['id'])->update(['status' => $want]);
        $this->success('处理成功');
    }

    public function want()
    {

        $user = $this->auth->getUser();
        $uid = $user['id'];
        $id = $this->request->param('id');
        $publishWorkModel = new Publishwork();
        $work = $publishWorkModel->where('id', $id)->find();

        $shopModel = new \app\admin\model\Shop();
        $shop = $this->adminShopInfo($uid);
        if ($shop['status'] != 1) {
            $this->error("该店铺还未审核通过，不允许处理");
        }
        error_log("===work=====" . json_encode($work));

        $shopUserJobModel = new Shopjobuser();
        $shopUserJob = $shopUserJobModel->where('jobid', $id)->where('uid', $work['uid'])->find();
        error_log("====shopUserJob=====" . json_encode($shopUserJob));
        if ($shopUserJob) {

            $this->error('你已入人才库，请勿重复添加');
        } else {
            $data = array();
            $data['uid'] = $work['uid'];
            $data['jobid'] = $id;
            $data['workid'] = $work['worktype'];
            $data['shopid'] = $shop['id'];
            $data['createtime'] = time();
            $data['status'] = 1;
            $shopUserJobModel->insert($data);
            $this->success('成功');
        }
    }


    public function jobDetail2()
    {


        $id = $this->request->param('id');

        $shopJobUserModel = new Shopjobuser();
        $shopJobUser = $shopJobUserModel->where('id', $id)->find();

        $shopJobModel = new Shopjob();
        $work = $shopJobModel->where('id', $shopJobUser['jobid'])->find();

        $userModel = new \app\admin\model\User();
        $user = $userModel->where('id', $shopJobUser['uid'])->find();
        $user['avatar'] = cdnurl($user['avatar'], true);
        $work['user'] = $user;
        $workTypeModel = new Worktype();
        $workType = $workTypeModel->where('id', $shopJobUser['workid'])->find();
        $work['workType'] = $workType;


        $userProfileModel = new Userprofile();
        $profile = $userProfileModel->where('uid', $user['id'])->find();

//        $workAddressModel = new Workaddress();
//        $address = $workAddressModel->where('id', $work['addressId'])->find();
//        $work['address'] = $address;
        $work['profile'] = $profile;

        $this->success('', $work);

    }

    public function jobDetail()
    {


        $id = $this->request->param('id');
        $publishWorkModel = new Publishwork();
        $work = $publishWorkModel->where('id', $id)->find();
        if (!$work) $this->error('工作数据异常');
        $userModel = new \app\admin\model\User();
        $user = $userModel->where('id', $work['uid'])->find();
        $user['avatar'] = cdnurl($user['avatar'], true);
        $work['user'] = $user;
        $work['worktime'] = date('Y-m-d h:i:s', $work['worktime']);
        $workTypeModel = new Worktype();
        $workType = $workTypeModel->where('id', $work['worktype'])->find();
        $work['workType'] = $workType;


        $userProfileModel = new Userprofile();
        $profile = $userProfileModel->where('uid', $user['id'])->find();

        $workAddressModel = new Workaddress();
        $address = $workAddressModel->where('id', $work['addressId'])->find();
        $work['address'] = $address;
        $work['profile'] = $profile;

        $this->success('', $work);

    }


    public function info()
    {

        $user = $this->auth->getUser();
        $uid = $user['id'];


        $shop = $this->adminShopInfo($uid);

        error_log("==shop==" . json_encode($shop));
        $shop['license'] = cdnurl($shop['license'], true);
        $img = explode(",", $shop['imgs']);

        $list = [];
        foreach ($img as $k => $v) {
            $list[] = cdnurl($v, true);
        }
        $shop['img'] = $list;
        $this->success('', $shop);

    }


    /**
     * 店铺的工作列表
     */
    public function workList()
    {


        $data = array();
        $litestorenewsModel = new Litestorenews();
        $banners = $litestorenewsModel->where('type', 2)->field('id,image,title')->select();
        foreach ($banners as $key => $val) {
            $banners[$key]['image'] = cdnurl($val['image'], true);
        }
        $data['banner'] = $banners;

        $page = $this->request->param('page');
        $limit = 1000;
        $offset = ($page - 1) * $limit;

        $userPublishWorkModel = new Publishwork();
        $where = array();
        $where['Publishwork.status'] = 1;
        $list = $userPublishWorkModel->with(['worktype', 'user'])->where($where)->limit($offset, $limit)->select();
        foreach ($list as $key => $val) {
            error_log("==avatar==".$val['user']['avatar']);
            $mobile = substr_replace($val['user']['mobile'], '****', 3, 4);
            $list[$key]['user']['mobile'] = $mobile;
            if($val['user']['avatar'] == ''){
               $list[$key]['user']['avatar'] = "https://bs2021.oss-cn-hangzhou.aliyuncs.com/bs_logo.jpg";
            }else{
                $list[$key]['user']['avatar'] = cdnurl($val['user']['avatar'], true);

            }

        }

        $data['list'] = $list;

        $this->success('成功', $data);

    }


    public function addprofile()
    {

        $user = $this->auth->getUser();
        $name = $this->request->param('name');
        $pid = $this->request->param('pid');
        $cid = $this->request->param('cid');
        $aid = $this->request->param('aid');
        $pname = $this->request->param('pname');
        $cname = $this->request->param('cname');
        $aname = $this->request->param('aname');
        $address = $this->request->param('address');
        $license = $this->request->param('license');
        $img = $this->request->param('img');

        $adminName = $this->request->param('adminName');
        $adminPhone = $this->request->param('adminPhone');
        $images = $this->request->param('images');
        $items = json_decode(htmlspecialchars_decode($images), true);

        error_log("=====images====" . json_encode($items));
        $imgs = "";
        for ($i = 0; $i < count($items); $i++) {
            $imgs = $imgs . $items[$i];
            if ($i != count($items) - 1) {
                $imgs = $imgs . ",";
            }
        }

        error_log("=====imgs====" . $imgs);


        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('uid', $user['id'])->where('is_online', 1)->find();
        if ($shop) {
            $id = $shopModel->insertGetId(['uid' => $user['id'], 'merchantName' => $name, 'provinceId' => $pid,
                'cityId' => $cid, 'areaId' => $aid, 'provinceName' => $pname, 'cityName' => $cname, 'areaName' => $aname,
                'address' => $address, 'license' => $license, 'createtime' => time(), 'imgs' => $img, 'adminName' => $adminName,
                'adminPhone' => $adminPhone, 'imgs' => $imgs]);
        } else {
            $id = $shopModel->insertGetId(['uid' => $user['id'], 'merchantName' => $name, 'provinceId' => $pid,
                'cityId' => $cid, 'areaId' => $aid, 'provinceName' => $pname, 'cityName' => $cname, 'areaName' => $aname,
                'address' => $address, 'license' => $license, 'createtime' => time(), 'imgs' => $img, 'adminName' => $adminName,
                'adminPhone' => $adminPhone, 'imgs' => $imgs, 'is_online' => 1]);
        }

        if ($id > 0) {
            $this->success('成功');
        } else {
            $this->error('完善地址失败');
        }

    }


    /**
     * 员工列表
     */
    public function userList()
    {


        $page = $this->request->param('page');
        $limit = 10;
        $offset = ($page - 1) * $limit;

        $user = $this->auth->getUser();
        $uid = $user['id'];


        $shop = $this->adminShopInfo($uid);


        $shopUserModel = new Shopuser();
        $list = $shopUserModel->where('shopid', $shop['id'])->with(['user', 'worktype'])->order('createtime', 'desc')->limit($limit, $offset)->select();
        foreach ($list as $key => $val) {
            $list[$key]['user']['avatar'] = cdnurl($val['user']['avatar'], true);
            $list[$key]['createtime'] = date("Y-m-d h:i", $val['createtime']);
        }
        $this->success('', $list);
    }

    /**
     * 工作记录列表
     */
    public function userWorkHistory()
    {

        $user = $this->auth->getUser();
        $uid = $user['id'];

        $shop = $this->adminShopInfo($uid);
        $page = $this->request->param('page');
        $limit = 10;
        $offset = ($page - 1) * $limit;

        $userWorkHistoryModel = new Workhistory();
        $list = $userWorkHistoryModel->where('companyid', $shop['id'])->with(['user', 'worktype', 'company'])->order('endtime', 'desc')->limit($limit, $offset)->select();
        foreach ($list as $key => $val) {
            $list[$key]['user']['avatar'] = cdnurl($val['user']['avatar'], true);
            $mobile = substr_replace($val['user']['mobile'], '****', 3, 4);
            $list[$key]['user']['mobile'] = $mobile;
            $list[$key]['endtime'] = date("Y-m-d h:i", $val['endtime']);
        }
        $this->success('', $list);
    }

    /**
     * 确定客钟
     */
    public function sureClock()
    {

        $user = $this->auth->getUser();
        $uid = $user['id'];

        $id = $this->request->param('id');

        $shopModel = new \app\admin\model\Shop();
        $shop = $this->adminShopInfo($uid);
        if (!$shop) {
            $this->error("没有权限");
        }
        $workHistoryModel = new Workhistory();
        $work = $workHistoryModel->where('id', $id)->find();

        error_log($shop['id'] . "==========" . $work['companyid']);
        if ($shop['id'] != $work['companyid']) {
            $this->error("权限不够");
        }
        $userAmountModel = new Useramount();
        $userModel = new \app\admin\model\User();
        $workUser = $userModel->where('id', $work['uid'])->find();
        $str = $workUser['username'] . "****" . substr($user['mobile'], 7, 11);
        $userAmountModel->insert(['uid' => $work['uid'], 'amount' => $work['backmoney'] * $work['clock'] * 0.3,
            'createtime' => time(), 'type' => 2, 'desc' => $str, 'extra' => $work['id']]);
        $workHistoryModel->where('id', $id)->update(['status' => 1]);


        $workTypeModel = new Worktype();
        $type = $workTypeModel->where('id', $work['workid'])->find();

        $refUser = $userModel->where('id', $workUser['ref_uid'])->find();
        $userAmountModel->insert(['uid' => $refUser['id'], 'amount' => $type['backmoney'] * $work['clock'] * 0.1,
            'createtime' => time(), 'type' => 5, 'desc' => "推荐用户" . $str, 'extra' => $work['id']]);

        $userTeamWorkTeamModel = new Userteamworkhistory();
        $userTeamWorkTeamModel->insert(['uid' => $refUser['id'], 'backmoney' => $type['backmoney'] * $work['clock'] * 0.1, 'clock' => $work['clock'], 'historyId' => $work['id'], 'workUserId' => $work['uid']]);

        $usermsgModel = new Usermsgweixin();
        $wx = $usermsgModel->where('user_id', $work['uid'])->find();
        if ($wx) {
            $t = $this->wxapp->template_message->send([
                'touser' => $wx['openid'],
                'template_id' => 'Zxz4oTWcxCpS1xNyoDbGUlLrR9G27buNPrpA5nHJVPM',
                'data' => [
                    'first' => "您好，您的工作记录 " . $work['clock'] . "客钟 " . "返点 已审核通过！",
                    'keyword1' => $shop['merchantName'],
                    'keyword2' => date("y-m-d h:i"),
                    'keyword3' => $work['backmoney'] * $work['clock'] * 0.3 . "元",
                    'remark' => '更多结算信息，请点击我的工作记录详情！',
                ],
            ]);

        }
        $refWx = $usermsgModel->where('user_id', $refUser['id'])->find();
        if ($refWx) {
            $t = $this->wxapp->template_message->send([
                'touser' => $refWx['openid'],
                'template_id' => 'UGjp5CSKqnH4h1rjErKPKu57VG6DSJE2wz5hbNH5U5c',
                'data' => [
                    'first' => "恭喜您，一笔佣金结算成功",
                    'keyword1' => "佣金来自 " . $str,
                    'keyword2' => "团队工作记录返现",
                    'keyword3' => "团队奖励",
                    'keyword4' => $type['backmoney'] * $work['clock'] * 0.1,
                    'remark' => '更多结算信息，请点击团队的工作记录详情！',
                ],
            ]);

        }


        $this->success('成功');
    }


    /**
     * 待处理的应聘列表
     */
    public function applyUserList()
    {


        $user = $this->auth->getUser();
        $uid = $user['id'];
        $page = $this->request->param('page');
        $limit = 10;
        $offset = ($page - 1) * $limit;

        $shop = $this->adminShopInfo($uid);

        $shopJobUserModel = new Shopjobuser();
        $list = $shopJobUserModel->where('shopid', $shop['id'])->with(['user', 'worktype'])->where('Shopjobuser.status', -1)->order('createtime', 'desc')->limit($limit, $offset)->select();
        foreach ($list as $key => $val) {
            $list[$key]['user']['avatar'] = cdnurl($val['user']['avatar'], true);
            $mobile = substr_replace($val['user']['mobile'], '****', 3, 4);
            $list[$key]['user']['mobile'] = $mobile;

            $list[$key]['createtime'] = date('Y-m-d h:i');
        }
        $this->success('', $list);
    }

    /**
     * 返利统计
     */
    public function backMoney()
    {

        $user = $this->auth->getUser();
        $uid = $user['id'];
        $page = $this->request->param('page');
        $limit = 10;
        $offset = ($page - 1) * $limit;

        $shop = $this->adminShopInfo($uid);

        $shopuserModel = new Shopuser();
        $total = $shopuserModel->where('shopId', $shop['id'])->where('status', 1)->count('id');
        $worktotal = $shopuserModel->where('shopId', $shop['id'])->where('status', 1)->group('workid')->count('id');
        $workhistoryModel = new Workhistory();
        $money = $workhistoryModel->where('companyid', $shop['id'])->where('status', 1)->sum('backmoney');
        $totalAmount = $workhistoryModel->where('companyid', $shop['id'])->where('status', 1)->sum('total');

        $data = array();
        $data['total'] = $total;
        $data['worktotal'] = $worktotal;
        $data['money'] = $money;
        $data['totalAmount'] = $totalAmount;



        $shopuserModel = new Shopuser();
        $list = $shopuserModel->with(['user', 'worktype'])->where('shopId', $shop['id'])->where('Shopuser.status', 1)->limit($limit, $offset)->select();
        foreach ($list as $key => $val) {
            $list[$key]['user']['avatar'] = cdnurl($val['user']['avatar'], true);
            $mobile = substr_replace($val['user']['mobile'], '****', 3, 4);
            $list[$key]['user']['mobile'] = $mobile;
        }
        $data['list'] = $list;
        $this->success('', $data);
    }

    /**
     * 发布工作
     */
    public function publish()
    {

        $user = $this->auth->getUser();
        $uid = $user['id'];
        $shopModel = new \app\admin\model\Shop();
        $shop = $this->adminShopInfo($uid);
        if (!$shop) {
            $this->error("没有权限");
        }
        if ($shop['status'] != 1) {
            $this->error("该店铺还未审核通过，不允许发布");
        }

        $workId = $this->request->param('workId');
        $money = $this->request->param('money');
        $tag = $this->request->param('tag');
        $mark = $this->request->param('mark');
        $title = $this->request->param('title');
        $num = $this->request->param('num');
        $require = $this->request->param('require');


        $companyid = $shop['id'];
        $createtime = time();
        $pid = $shop['provinceId'];
        $cid = $shop['cityId'];
        $aid = $shop['areaId'];

        $shopWorkModel = new Shopjob();
        $id = $shopWorkModel->insertGetId(['title' => $title, 'num' => $num, 'require' => $require, 'createtime' => $createtime, 'workid' => $workId,
            'companyid' => $companyid, 'amount' => $money, 'tag' => $tag,
            'pid' => $pid, 'cid' => $cid, 'aid' => $aid, 'status' => -1, 'mark' => $mark]);

        if ($id > 0) {
            $this->success('发布成功');
        } else {
            $this->success('发布失败');

        }

    }


    /**
     *
     * 获取店铺列表
     */
    public function selectShopList()
    {

        $user = $this->auth->getUser();
        $uid = $user['id'];
        $shopModel = new \app\admin\model\Shop();
        $sql = "select s.id as id ,s.merchantName as name from u_shop s left join u_shop_admin sa on s.id != sa.shopid where s.uid = " . $uid;
        error_log("==sqk==" . $sql);
        $shopList = $shopModel->query($sql);
        $this->success('', $shopList);
    }

    /**
     * 添加店铺
     */
    public function addShopAdmin()
    {

        $user = $this->auth->getUser();
        $uid = $user['id'];
        $shopId = $this->request->param('shopId');
        $name = $this->request->param('name');
        $phone = $this->request->param('phone');


        $shopAdminModel = new Shopadmin();
        $userModel = new \app\admin\model\User();
        $u = $userModel->where('mobile', $phone)->find();

        $isAdd = $shopAdminModel->where('shopid', $shopId)->find();
        if ($isAdd) {
            $this->error('此店铺已添加了店长，不需要再添加');
        }
        $adminUid = -1;
        if ($u) {
            $shopAdmin = $shopAdminModel->where('uid', $u['id'])->find();
            if ($shopAdmin) {
                $this->error('此号码已是店长，不能添加');
            }
            $userModel->where('id', $u['id'])->update(['is_shop' => 1]);
            $adminUid = $u['id'];
        } else {

            $salt = Random::alnum();
            $password = $this->auth->getEncryptPassword($phone, $salt);
            $adminUid = $userModel->insertGetId(['username' => $name, 'group_id' => 1, 'salt' => $salt, 'password' => $password, 'mobile' => $phone, 'ref_uid' => $uid, 'is_shop' => 1]);
        }

        $shopAdminModel = new Shopadmin();
        $shopAdminModel->insert(['shopid' => $shopId, 'uid' => $adminUid, 'createtime' => time(), 'addUid' => $uid]);
        $this->success('成功');
    }


    /**
     * 我的店长列表
     */
    public function adminList()
    {

        $user = $this->auth->getUser();
        $uid = $user['id'];
        $adminModel = new Shopadmin();
        $list = $adminModel->with(['user', 'shop'])->where('addUid', $uid)->select();
        foreach ($list as $key => $val) {
            if ($val['user']['avatar'] != '') {
                $list[$key]['user']['avatar'] = cdnurl($val['user']['avatar'], true);
            } else {
                $list[$key]['user']['avatar'] = "https://bs2021.oss-cn-hangzhou.aliyuncs.com/bs_logo.jpg";
            }
        }
        $this->success('', $list);
    }

    /**
     * 删除
     */
    public function deleteAdmin()
    {

        $user = $this->auth->getUser();
        $uid = $user['id'];
        $id = $this->request->param('id');
        $adminModel = new Shopadmin();
        $admin = $adminModel->where('id', $id)->find();
        if (!$admin) {
            $this->error('数据不存在');
        }
        if ($admin['addUid'] != $uid) {
            $this->error('无期限操作');
        }

        $userModel = new \app\admin\model\User();
        $userModel->where('id', $admin['uid'])->update(['is_shop' => -1]);
        $adminModel->where('id', $id)->delete();
        $this->success('删除成功');
    }

    /**
     * 我的店铺列表
     */
    public function shopList()
    {

        $user = $this->auth->getUser();
        $uid = $user['id'];
        $shopModel = new \app\admin\model\Shop();
        $list = $shopModel->where('uid', $uid)->select();
        foreach ($list as $key => $val) {
            $list[$key]['img'] = cdnurl(explode(",", $val['imgs'])[0], true);
        }

        $this->success('', $list);

    }


    /**
     * 更改状态
     */
    public function updateOnlineStatus()
    {

        $uid = $this->request->param('id');
        $shopId = $this->request->param('shopId');
        $shopModel = new \app\admin\model\Shop();
        $shopModel->where('uid', $uid)->update(['is_online' => -1]);
        $shopModel->where('id', $shopId)->update(['is_online' => 1]);
        $this->success('');
    }

}
